<template>
  <el-row :gutter="24">
    <el-col :span="14" :xs="24">
      <ContentWrap>
        <el-form
          ref="formRef"
          :model="formData"
          :rules="formRules"
          label-width="150px"
          v-loading="formLoading"
        >
          <el-row>
            <el-col :span="24">
              <el-form-item label="设备图片" prop="picUrl">
                <UploadImg
                  v-model="formData.picUrl"
                  @change="handleImageChange"
                  :deviceId="formData.id ?? '0'"
                  :picUrl="formData.picUrl ? formData.picUrl : ''"
                />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="12">
              <el-form-item label="设备分组" prop="groupId">
                <el-tree-select
                  v-model="formData.groupId"
                  :data="dataList"
                  :props="defaultProps"
                  check-strictly
                  node-key="id"
                  placeholder="请选择分组"
                  class="!w-240px"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="设备服务器" prop="mqttConfigId">
                <el-select v-model="formData.mqttConfigId" placeholder="请选择设备服务器">
                  <el-option
                    v-for="item in mqttConfigList"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                    class="!w-240px"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="设备类型" prop="deviceType">
                <el-select
                  v-model="formData.deviceType"
                  placeholder="请选择设备类型"
                  clearable
                  class="!w-240px"
                >
                  <el-option
                    v-for="dict in getIntDictOptions(DICT_TYPE.MQTT_DEVICE_TYPE)"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="网关SN编号" prop="gatewayId">
                <el-input v-model="formData.gatewayId" placeholder="网关SN编号" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="设备名称" prop="deviceName">
                <el-input v-model="formData.deviceName" placeholder="设备名称" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="12">
              <el-form-item label="报警状态" prop="alarmStatus">
                <el-radio-group v-model="formData.alarmStatus">
                  <el-radio
                    v-for="dict in getStrDictOptions(DICT_TYPE.MQTT_CONFIG_ENABLED)"
                    :key="dict.value"
                    :value="dict.value"
                  >
                    {{ dict.label }}
                  </el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="报警设置" prop="alarmDefult">
                <el-radio-group v-model="formData.alarmDefult">
                  <el-radio
                    v-for="dict in getStrDictOptions(DICT_TYPE.MQtt_DEVICE_DEFULT_ALERM)"
                    :key="dict.value"
                    :value="dict.value"
                  >
                    {{ dict.label }}
                  </el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="设备的固件编号" prop="firmwareId">
                <el-input v-model="formData.firmwareId" placeholder="请输入设备的固件编号" />
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="设备唯一标识符" prop="deviceKey">
                <el-input
                  v-model="formData.deviceKey"
                  placeholder="唯一标识符"
                  :disabled="formData.deviceKey != null"
                >
                  <template #suffix>
                    <el-button
                      icon="Refresh"
                      :disabled="formData.deviceKey != null"
                      @click="generateDeviceKey"
                      type="primary"
                      size="small"
                      style="margin-right: -12px"
                      >生成</el-button
                    >
                  </template>
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <el-col :span="24">
            <el-form-item label="设备编号" prop="serialNumber">
              <el-input v-model="formData.serialNumber" placeholder="请输入设备序列号" />
            </el-form-item>
          </el-col>

          <el-row>
            <el-col :span="24">
              <el-form-item label="设备所在地" prop="address">
                <el-input v-model="formData.address" placeholder="设备所在地" readonly>
                  <template #suffix>
                    <el-button
                      icon="el-icon-location"
                      @click="openMapDialog"
                      type="primary"
                      style="margin-right: -12px"
                      >地图</el-button
                    >
                  </template>
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="经度" prop="longitude">
                <el-input v-model="formData.longitude" placeholder="经度" readonly />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="纬度" prop="latitude">
                <el-input v-model="formData.latitude" placeholder="纬度" readonly />
              </el-form-item>
            </el-col>
          </el-row>

          <el-form-item label="备注" prop="nickname">
            <el-input v-model="formData.nickname" placeholder="备注" />
          </el-form-item>
        </el-form>
        <div style="text-align: right">
          <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
        </div>
      </ContentWrap>
    </el-col>

    <!-- 右侧信息面板 -->
    <el-col :span="10" :xs="24">
      <!-- 设备二维码 -->
      <!-- <ContentWrap style="margin-bottom: 18px">
        <div class="header">
          <h3>设备二维码</h3>
          <el-button type="primary" size="small" @click="showQRCode" :disabled="!formData.id">
            查看二维码
          </el-button>
        </div>
        <div v-if="qrCodeData" class="qr-code-container">
          <img :src="qrCodeData.qrcode" alt="设备二维码" />
          <p style="margin-top: 10px; color: #666">设备二维码</p>
        </div>
        <div v-else class="qr-code-placeholder"> 点击按钮查看设备二维码 </div>
      </ContentWrap> -->

      <!-- 网关概况 -->
      <ContentWrap>
        <div class="header"><h3>网关概况</h3></div>
        <el-descriptions :column="1" border>
          <el-descriptions-item label="SN编号">{{
            formGetewayData.gatewayId
          }}</el-descriptions-item>

          <el-descriptions-item label="固件版本">{{
            formGetewayData.firmwareVersion
          }}</el-descriptions-item>
          <el-descriptions-item label="联网方式">
            <el-link type="primary">{{ formGetewayData.networkType }}</el-link>
          </el-descriptions-item>
          <el-descriptions-item label="网关状态">
            <el-tag type="success">{{ formGetewayData.getewayStatus }}</el-tag>
          </el-descriptions-item>
        </el-descriptions>
        <div style="margin-top: 16px">
          <el-button type="primary" size="small">网关信息查询</el-button>
          <el-button type="primary" size="small">联网信息查询</el-button>
        </div>
      </ContentWrap>
    </el-col>
  </el-row>

  <el-dialog v-model="mapDialogVisible" title="选择位置" width="60%" @opened="onMapDialogOpened">
    <TencentMapSelector
      ref="mapSelectorRef"
      @location-selected="onLocationSelected"
      :address="formData.address"
      :longitude="formData.longitude"
      :latitude="formData.latitude"
    />
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue'
import { getIntDictOptions, getStrDictOptions, DICT_TYPE } from '@/utils/dict'
import { DeviceApi, DeviceVO } from '@/api/mqtt/device'
import UploadImg from './upload.vue'
import type { UploadFile } from 'element-plus'
import { ConfigApi } from '@/api/mqtt/config'
import TencentMapSelector from './TencentMapSelector.vue'
import { defaultProps } from '@/utils/tree'

// 监听 props.device 的变化
const props = defineProps({
  device: Object
})
watch(
  () => props.device,
  async (newVal, oldVal) => {
    if (newVal) {
      console.log('watch props.device : ' + JSON.stringify(newVal))
      const res = await DeviceApi.getDevice(newVal.id)
      formData.value = res as DeviceVO
      formGetewayData.value = res
      // formData.value = { ...newVal } // 深拷贝对象
    }
  }
)

const mapDialogVisible = ref(false)
const mapSelectorRef = ref()
const openMapDialog = () => {
  mapDialogVisible.value = true
}
const onMapDialogOpened = () => {
  mapSelectorRef.value?.initMap?.()
  // 新增：有地址时自动定位
  if (formData.value.address) {
    mapSelectorRef.value?.locateByAddress?.(formData.value.address)
  }
}
const onLocationSelected = ({ address, longitude, latitude }) => {
  formData.value.address = address
  formData.value.longitude = longitude
  formData.value.latitude = latitude
  mapDialogVisible.value = false
}
/** IoT 设备 表单 */
defineOptions({ name: 'DeviceForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref<Partial<DeviceVO>>({
  id: undefined,
  deviceKey: undefined,
  mqttConfigId: undefined,
  alarmStatus: '1',
  alarmDefult: '0',
  deviceName: undefined,
  nickname: undefined,
  serialNumber: undefined,
  picUrl: undefined,
  groupId: undefined,
  productId: undefined,
  productKey: undefined,
  deviceType: undefined,
  gatewayId: undefined,
  state: undefined,
  onlineTime: undefined,
  offlineTime: undefined,
  activeTime: undefined,
  ip: undefined,
  firmwareId: undefined,
  deviceSecret: undefined,
  mqttClientId: undefined,
  mqttUsername: undefined,
  mqttPassword: undefined,
  authType: undefined,
  latitude: undefined,
  longitude: undefined,
  areaId: undefined,
  address: undefined,
  config: undefined
})
const formRules = reactive({
  groupId: [{ required: true, message: '请选择设备分组', trigger: 'change' }],
  mqttConfigId: [{ required: true, message: '请选择设备服务器', trigger: 'change' }],
  deviceType: [{ required: true, message: '请选择设备类型', trigger: 'change' }],
  deviceKey: [{ required: true, message: '设备唯一标识符不能为空', trigger: 'blur' }],
  deviceName: [{ required: true, message: '设备名称不能为空', trigger: 'blur' }],
  address: [{ required: true, message: '请选择设备地址', trigger: 'blur' }],
  state: [{ required: true, message: '设备状态', trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref
const uploadRef = ref() // 上传组件 Ref
const mqttConfigList = ref<any[]>([]) // mqtt配置列表
// 存储上传的文件对象
const uploadedFile = ref<UploadFile | null>(null)

// 二维码相关
const qrCodeData = ref<{ deviceKey: string; qrcode: string } | null>(null)

// 处理图片变化
const handleImageChange = (file: UploadFile | null) => {
  console.log('图片变化:', file)
  uploadedFile.value = file
}

const dataList = ref<Tree[]>([]) // 树形结构

const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()

  // 处理图片上传（如果有文件需要上传到服务器）
  if (uploadedFile.value && uploadedFile.value.raw) {
    try {
      // 临时使用本地URL（实际项目中应该上传到服务器）
      formData.value.picUrl = uploadedFile.value.url || undefined
    } catch (error) {
      console.error('图片上传失败:', error)
      message.error('图片上传失败，请重试')
      return
    }
  }

  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as DeviceVO
    if (formType.value === 'create') {
      await DeviceApi.createDevice(data)
      message.success(t('common.createSuccess'))
    } else {
      await DeviceApi.updateDevice(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    // emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 生成设备唯一标识符 */
const generateDeviceKey = () => {
  // 生成12位UUID
  const chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'
  let uuid = ''
  for (let i = 0; i < 12; i++) {
    uuid += chars[Math.floor(Math.random() * chars.length)]
  }
  formData.value.deviceKey = uuid
  // message.success('设备唯一标识符生成成功')
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    deviceKey: undefined,
    mqttConfigId: undefined,
    deviceName: undefined,
    nickname: undefined,
    serialNumber: undefined,
    picUrl: undefined,
    groupId: undefined,
    productId: undefined,
    productKey: undefined,
    deviceType: undefined,
    gatewayId: undefined,
    state: undefined,
    onlineTime: undefined,
    offlineTime: undefined,
    activeTime: undefined,
    ip: undefined,
    firmwareId: undefined,
    deviceSecret: undefined,
    mqttClientId: undefined,
    mqttUsername: undefined,
    mqttPassword: undefined,
    authType: undefined,
    latitude: undefined,
    longitude: undefined,
    areaId: undefined,
    address: undefined,
    config: undefined
  }
  formRef.value?.resetFields()

  // 清空上传的文件
  uploadedFile.value = null
  // 清空上传组件
  uploadRef.value?.clearFile()
}

//

const formGetewayData = ref({
  id: undefined,
  gatewayId: undefined,
  getewayStatus: undefined,
  firmwareVersion: undefined,
  firmwareId: undefined,
  networkType: undefined
})

onMounted(async () => {
  resetForm()
  // console.log('onMounted props.device : ' + JSON.stringify(props.device))
  const res = await DeviceApi.getDevice(props.device?.id)
  formData.value = res as DeviceVO
  formGetewayData.value = res

  await ConfigApi.getConfigPage({ page: 1, size: 100 }).then((res) => {
    mqttConfigList.value = res.list
  })
})
</script>

<style scoped>
.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.header h3 {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.qr-code-container {
  text-align: center;
  padding: 20px;
  background: #fafafa;
  border-radius: 8px;
  border: 1px dashed #d9d9d9;
}

.qr-code-container img {
  max-width: 200px;
  max-height: 200px;
  border-radius: 4px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.qr-code-placeholder {
  text-align: center;
  padding: 40px;
  color: #999;
  background: #fafafa;
  border-radius: 8px;
  border: 1px dashed #d9d9d9;
}
</style>
